import React, { useState } from 'react';
import styled from 'styled-components';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { logInfo, logError } from '../logger';
import { sendVerificationCode, register as registerApi } from '../services/api';
import Modal from '../components/Modal';

const RegisterContainer = styled.div`
  max-width: 400px;
  margin: 2rem auto;
  padding: 2rem;
  background: ${props => props.theme.colors.cardBackground};
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
`;

const Title = styled.h2`
  text-align: center;
  margin-bottom: 1.5rem;
  color: ${props => props.theme.colors.textPrimary};
`;

const Form = styled.form`
  display: flex;
  flex-direction: column;
  gap: 1rem;
`;

const InputGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
`;

const Label = styled.label`
  font-weight: 500;
  color: ${props => props.theme.colors.textSecondary};
`;

const Input = styled.input`
  padding: 0.75rem;
  border: 1px solid ${props => props.theme.colors.border};
  border-radius: 8px;
  background: ${props => props.theme.colors.inputBackground};
  color: ${props => props.theme.colors.textPrimary};
  font-size: 1rem;

  &:focus {
    outline: none;
    border-color: ${props => props.theme.colors.primary};
    box-shadow: 0 0 0 2px ${props => props.theme.colors.primary}20;
  }
`;

const Button = styled.button`
  padding: 0.75rem;
  background: ${props => props.theme.colors.primary};
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;

  &:hover {
    background: ${props => props.theme.colors.primaryHover};
  }

  &:disabled {
    background: ${props => props.theme.colors.disabled};
    cursor: not-allowed;
  }
`;

const ErrorMessage = styled.div`
  color: ${props => props.theme.colors.error};
  font-size: 0.875rem;
  text-align: center;
  padding: 0.5rem;
  background: ${props => props.theme.colors.errorBackground};
  border-radius: 4px;
`;

const LinkContainer = styled.div`
  text-align: center;
  margin-top: 1rem;
  color: ${props => props.theme.colors.textSecondary};

  a {
    color: ${props => props.theme.colors.primary};
    text-decoration: none;
    margin-left: 0.25rem;

    &:hover {
      text-decoration: underline;
    }
  }
`;

const Register = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [showModal, setShowModal] = useState(false); // 控制模态框显示
  const [registeredEmail, setRegisteredEmail] = useState(''); // 保存注册成功的邮箱
  const [registeredPassword, setRegisteredPassword] = useState(''); // 保存注册成功的密码
  const navigate = useNavigate();
  const { login } = useAuth();

  // 倒计时效果
  React.useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    // 基本验证
    if (!verificationCode) {
      setError('请输入邮箱验证码');
      setLoading(false);
      return;
    }

    if (password !== confirmPassword) {
      setError('两次输入的密码不一致');
      setLoading(false);
      return;
    }

    if (password.length < 6) {
      setError('密码长度至少为6位');
      setLoading(false);
      return;
    }

    try {
      logInfo('用户尝试注册', { email });
      
      // 直接调用API进行注册
      const data = await registerApi({ username: name, email, password, verificationCode });

      logInfo('用户注册成功', { email });
      // 保存注册信息并显示模态框
      setRegisteredEmail(email);
      setRegisteredPassword(password);
      setShowModal(true);
      // 不再直接登录，而是通过模态框选择
    } catch (err) {
      logError('用户注册失败', { email, error: err.message });
      setError(err.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    if (!email) {
      setError('请输入邮箱地址');
      return;
    }

    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setError('请输入有效的邮箱地址');
      return;
    }

    setSendingCode(true);
    setError('');

    try {
      await sendVerificationCode({ email });
      setCountdown(60); // 设置60秒倒计时
    } catch (err) {
      console.error('验证码发送失败:', err);
      let errorMessage = '验证码发送失败，请稍后重试';
      
      // 根据错误类型提供更具体的错误信息
      if (err.message && err.message.includes('Network Error')) {
        errorMessage = '网络连接错误，请检查网络后重试';
      } else if (err.response && err.response.status === 429) {
        errorMessage = '发送过于频繁，请稍后再试';
      } else if (err.response && err.response.status >= 500) {
        errorMessage = '服务器暂时不可用，请稍后再试';
      }
      
      setError(errorMessage);
    } finally {
      setSendingCode(false);
    }
  };

  // 处理模态框中的登录操作
  const handleLogin = async () => {
    try {
      // 使用认证上下文登录用户
      await login({ email: registeredEmail, password: registeredPassword });
      // 关闭模态框
      setShowModal(false);
      // 重定向到个人中心
      navigate('/profile');
    } catch (err) {
      logError('模态框中登录失败', { email: registeredEmail, error: err.message });
      setError(err.message || '登录失败');
      // 关闭模态框
      setShowModal(false);
    }
  };

  // 处理模态框关闭操作
  const handleCloseModal = () => {
    setShowModal(false);
    // 重定向到登录页面
    navigate('/login');
  };

  return (
    <RegisterContainer>
      <Title>用户注册</Title>
      <Form onSubmit={handleSubmit}>
        <InputGroup>
          <Label htmlFor="name">姓名</Label>
          <Input
            id="name"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            placeholder="请输入姓名"
          />
        </InputGroup>
        
        <InputGroup>
          <Label htmlFor="email">邮箱</Label>
          <Input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            placeholder="请输入邮箱"
          />
        </InputGroup>
        
        <InputGroup>
          <Label htmlFor="verificationCode">验证码</Label>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <Input
              id="verificationCode"
              type="text"
              value={verificationCode}
              onChange={(e) => setVerificationCode(e.target.value)}
              required
              placeholder="请输入验证码"
              style={{ flex: 1 }}
            />
            <Button 
              type="button" 
              onClick={handleSendCode} 
              disabled={sendingCode || countdown > 0}
              style={{ flexShrink: 0, padding: '0.5rem 1rem', height: '42px' }}
            >
              {sendingCode ? '发送中...' : countdown > 0 ? `${countdown}秒后重发` : '发送验证码'}
            </Button>
          </div>
        </InputGroup>
        
        <InputGroup>
          <Label htmlFor="password">密码</Label>
          <Input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            placeholder="请输入密码（至少6位）"
          />
        </InputGroup>
        
        <InputGroup>
          <Label htmlFor="confirmPassword">确认密码</Label>
          <Input
            id="confirmPassword"
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            required
            placeholder="请再次输入密码"
          />
        </InputGroup>
        
        {error && <ErrorMessage>{error}</ErrorMessage>}
        
        <Button type="submit" disabled={loading}>
          {loading ? '注册中...' : '注册'}
        </Button>
      </Form>
      
      <LinkContainer>
        已有账号？
        <Link to="/login">立即登录</Link>
      </LinkContainer>
      
      {/* 注册成功后的模态框 */}
      <Modal
        isOpen={showModal}
        onClose={handleCloseModal}
        onConfirm={handleLogin}
        title="注册成功"
        message="恭喜您注册成功！点击登录按钮可立即登录，点击关闭按钮将跳转到登录页面。"
        confirmText="登录"
        closeText="关闭"
      />
    </RegisterContainer>
  );
};

export default Register;